package scanner.com.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import scanner.com.entity.ContactEntity;
import scanner.com.entity.DatabasesEntity;

/**
 * Created by Administrator on 2016/6/17.
 */
public class DBHelper extends SQLiteOpenHelper {
    private static DBHelper Single;

    public static DBHelper getInstance(Context context) {
        if(Single == null) Single = new DBHelper(context);
        return Single;
    }

    private static final String DB_NAME = "scanner.db";
    private static final int DB_VERSION = 2;

    private static final String HISTORY_TABLE_NAME = "history";
    private static final String HISTORY_KEY_RECORD_ID= "_id";
    private static final String HISTORY_KEY_QR_TYPE = "qr_type";
    private static final String HISTORY_KEY_QR_CONTENT = "qr_content";
    private static final String HISTORY_KEY_QR_FROM = "qr_from";
    private static final String HISTORY_KEY_QR_TIME = "qr_time";

    private static final String CRATE_HISTORY_TABLE_SQL = "CREATE TABLE " + HISTORY_TABLE_NAME + " ("
            + HISTORY_KEY_RECORD_ID  +" INTEGER PRIMARY KEY AUTOINCREMENT, "
            + HISTORY_KEY_QR_TYPE +" TINYINT,"
            + HISTORY_KEY_QR_CONTENT +" TEXT,"
            + HISTORY_KEY_QR_FROM +" BOOLEAN,"
            + HISTORY_KEY_QR_TIME +" DATETIME DEFAULT (datetime('now','localtime')))";


    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CRATE_HISTORY_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + HISTORY_TABLE_NAME);
        onCreate(db);
    }

    private SQLiteDatabase getDatabase(){
        SQLiteDatabase db = null;
        try{
            db = getWritableDatabase();
        } catch (SQLiteException e){
            Log.e("SamLog","数据库操作失败");
            e.printStackTrace();
        }
        return db;
    }

    public boolean insertRecord(DatabasesEntity DatabasesEntity){
        ContentValues contentValues = new ContentValues();
        if(DatabasesEntity.getId() > 0) contentValues.put(HISTORY_KEY_RECORD_ID,DatabasesEntity.getId());
        DatabasesEntity.RECORD_TYPE recordType = DatabasesEntity.getRecordType();
        contentValues.put(HISTORY_KEY_QR_TYPE,recordType.getTypeValue());
        if(recordType == scanner.com.entity.DatabasesEntity.RECORD_TYPE.CONTACT){
            contentValues.put(HISTORY_KEY_QR_CONTENT,(ContactEntity.toVCardFormat((ContactEntity)DatabasesEntity.getRecordContent())));
        } else {
            contentValues.put(HISTORY_KEY_QR_CONTENT,((String)DatabasesEntity.getRecordContent()));
        }
        contentValues.put(HISTORY_KEY_QR_FROM,DatabasesEntity.getRecordFrom().getValue());
        contentValues.put(HISTORY_KEY_QR_TIME,DatabasesEntity.getRecordTime());
        return getDatabase().insert(HISTORY_TABLE_NAME,null,contentValues) != -1;
    }

    public void deleteRecord(int recordId){
        getDatabase().delete(HISTORY_TABLE_NAME,HISTORY_KEY_RECORD_ID + " = "+recordId,null);
//        getDatabase().delete(HISTORY_TABLE_NAME,HISTORY_KEY_RECORD_ID + " = ?",new String[]{recordId+""});
    }

    public List<DatabasesEntity> getAllRecords(){
        Cursor cursor = getDatabase().rawQuery("SELECT * FROM " + HISTORY_TABLE_NAME,null);
        List<DatabasesEntity> DatabasesEntityList = null;
        if(cursor != null) {
            DatabasesEntityList = new ArrayList<>();
            while (cursor.moveToNext()) {
                DatabasesEntity DatabasesEntity = new DatabasesEntity();
                DatabasesEntity.setId(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_RECORD_ID)));
                DatabasesEntity.RECORD_TYPE recordType = scanner.com.entity.DatabasesEntity.RECORD_TYPE.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                DatabasesEntity.setRecordType(recordType);
                String contentStr = cursor.getString(cursor.getColumnIndex(HISTORY_KEY_QR_CONTENT));
                if(recordType == scanner.com.entity.DatabasesEntity.RECORD_TYPE.CONTACT){
                    DatabasesEntity.setRecordContent(ContactEntity.parseFromVCard(contentStr));
                } else DatabasesEntity.setRecordContent(contentStr);
                DatabasesEntity.RECORD_FROM recordFrom = scanner.com.entity.DatabasesEntity.RECORD_FROM.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                DatabasesEntity.setRecordFrom(recordFrom);
                String time = cursor.getString(cursor.getColumnIndex(HISTORY_KEY_QR_TIME));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long timeStamp = System.currentTimeMillis();
                try {
                    timeStamp = simpleDateFormat.parse(time).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DatabasesEntity.setRecordTime(timeStamp);
                DatabasesEntityList.add(DatabasesEntity);
            }
        }
        return DatabasesEntityList;
    }
}
